package com.cheyun.netsalev3.dataSource

import androidx.lifecycle.MutableLiveData
import androidx.paging.PageKeyedDataSource
import com.cheyun.netsalev3.repository.BasePageRepository
import com.cheyun.netsalev3.utils.api.NetworkState

/**
 * 分页数据源
 */
class StockDataSource2<T>(var listener: BasePageRepository<T>, var networkState: MutableLiveData<NetworkState>) : PageKeyedDataSource<Int, T>() {

    override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, T>) {

        networkState.postValue(NetworkState.LOADING)
        var method: (data: MutableList<T>) -> Unit = {
            callback.onResult(it, null, 2)
            networkState.postValue(NetworkState.LOADED)
        }
        listener.loadInitial(params, method)
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, T>) {
        listener.loadAfter(params, callback)
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, T>) {
        if (params.key - 1 <= 0) {
            return
        }
        listener.loadBefore(params, callback)
    }
}


